package org.nudt.system.controller

import com.fasterxml.jackson.databind.ObjectMapper
import org.nudt.common.exception.BadRequestException
import org.nudt.common.model.ResponseData
import org.nudt.common.utils.FileUtil
import org.nudt.system.service.FileService
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import java.io.File

@RestController
@RequestMapping("/v1/file")
class FileController(
    private val fileService: FileService,
    private val objectMapper: ObjectMapper,
) {
    
    private val logger = LoggerFactory.getLogger(FileController::class.java)
    
    @PostMapping("/upload/image")
    fun uploadImage(@RequestParam("file") file: MultipartFile): ResponseData<String> {
        // 定义支持的图片格式
        val imageTypes = "jpg png jpeg webp"
        // 获取文件扩展名
        val fileExt = FileUtil.getExtensionName(file.originalFilename)
        // 检查文件格式
        if (fileExt != null && !imageTypes.contains(fileExt)) {
            throw BadRequestException("文件格式错误！, 仅支持 $imageTypes 格式")
        }
        return ResponseData.success(fileService.upload(file))
    }
    
    @GetMapping("/ffmpeg")
    fun ffmpeg() {
        val rootDir = File("D:\\input")
        val destRootDir = File("D:\\output")
        val firstDir = rootDir.listFiles()
        // it1 是第一层数字文件夹
        firstDir?.forEach { it1 ->
            if (it1.isDirectory) {
                val secondDir = it1.listFiles()
                // it2是第二层数字文件夹,对应一个视频
                secondDir?.forEach { it2 ->
                    var destFile: File? = null
                    var entry: Entry
                    var audio: File? = null
                    var video: File? = null
                    if (it2.isDirectory) {
                        val thirdDir = it2.listFiles()
                        // it3是entry.json或者是文件夹
                        thirdDir?.forEach { it3 ->
                            if (it3.isFile && it3.name == "entry.json") {
                                try {
                                    entry = objectMapper.readValue(it3, Entry::class.java)
                                    // 视频文件名
                                    var name = ""
                                    if (secondDir.size == 1) {
                                        name = entry.title.replace("|", "")
                                    } else {
                                        if (entry.page_data != null) {
                                            name = entry.page_data!!.part
                                        } else if (entry.ep != null) {
                                            name = entry.ep!!.index_title
                                        }
                                    }
                                    // logger.info(it1.name)
                                    val destDir = File(destRootDir, entry.owner_name)
                                    // 多集的目标文件夹不存在时就新建
                                    if (!destDir.exists()) destDir.mkdir()
                                    if (name.isNotEmpty()) {
                                        destFile = File(destDir, "$name.mp4")
                                    }
                                } catch (e: Exception) {
                                    logger.info(it1.readText())
                                    logger.info(it3.readText())
                                }
                            } else if (it3.isDirectory) {
                                val fourthDir = it3.listFiles()
                                fourthDir?.forEach { it4 ->
                                    if (it4.isFile && it4.name == "audio.m4s") {
                                        audio = it4
                                    }
                                    if (it4.isFile && it4.name == "video.m4s") {
                                        video = it4
                                    }
                                }
                            }
                            if (destFile != null && audio != null && video != null) {
                                if (!destFile!!.exists()) {
                                    fileService.ffmpegVideo(destFile!!, audio!!, video!!, it1)
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

data class Entry(
    val title: String,
    val video_quality: String,
    val owner_name: String,
    val page_data: pageData?,
    val ep: Ep?
)

data class pageData(
    val page: Int,
    val part: String,
)

data class Ep(
    val page: Int,
    val index_title: String,
)